package yh.thread.threadstate;

/**
 *
 * 模拟 java 中线程死锁
 * @author: zyh
 * @date: 2024/10/11 15:34
 **/
public class DeadlockExample {
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("Thread 1: Holding lock 1...");

                try { Thread.sleep(100); } catch (InterruptedException e) {}

                System.out.println("Thread 1: Waiting for lock 2...");
                synchronized (lock2) {
                    System.out.println("Thread 1: Acquired lock 2!");
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("Thread 2: Holding lock 2...");

                try { Thread.sleep(100); } catch (InterruptedException e) {}

                System.out.println("Thread 2: Waiting for lock 1...");
                synchronized (lock1) {
                    System.out.println("Thread 2: Acquired lock 1!");
                }
            }
        });

        thread1.start();
        thread2.start();
    }


    /**
     * 日志打印结果
      Found one Java-level deadlock:
     =============================
     "Thread-1":
     waiting to lock monitor 0x00007fe96f00e2b8 (object 0x00000007156e68a0, a java.lang.Object),
     which is held by "Thread-0"
     "Thread-0":
     waiting to lock monitor 0x00007fe96f010d58 (object 0x00000007156e68b0, a java.lang.Object),
     which is held by "Thread-1"

     Java stack information for the threads listed above:
     ===================================================
     "Thread-1":
     at yh.thread.threadstate.DeadlockExample.lambda$main$1(DeadlockExample.java:35)
     - waiting to lock <0x00000007156e68a0> (a java.lang.Object)
     - locked <0x00000007156e68b0> (a java.lang.Object)
     at yh.thread.threadstate.DeadlockExample$$Lambda$2/2129789493.run(Unknown Source)
     at java.lang.Thread.run(Thread.java:748)
     "Thread-0":
     at yh.thread.threadstate.DeadlockExample.lambda$main$0(DeadlockExample.java:21)
     - waiting to lock <0x00000007156e68b0> (a java.lang.Object)
     - locked <0x00000007156e68a0> (a java.lang.Object)
     at yh.thread.threadstate.DeadlockExample$$Lambda$1/1607521710.run(Unknown Source)
     at java.lang.Thread.run(Thread.java:748)

     Found 1 deadlock.
     **/
}
